﻿using Dapper;
using Dapper.Contrib.Extensions;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.DLL.PermissionDLL
{
    /// <summary>
    /// 权限信息
    /// </summary>
    public class PermissionBusiness : Base.BaseDLL, IPermissionBusiness
    {
        public PermissionBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {
        }

        public bool Delete(long AutoId) => dbConnection.Execute(@$"delete  from `permissionres` where permissionid ={AutoId};
                                                                    delete  from buttons_permission where permissionid = {AutoId};
                                                                    delete  from Permission where autoid = {AutoId};") >= 0;

        public bool Edit(Permission data) => this.dbConnection.Update(data);

        public Permission FristDefault(long AutoId) => this.dbConnection.Get<Permission>(AutoId);

        public List<PermissionTable> Get(long AutoId) => dbConnection.Query<PermissionTable>($"SELECT a.autoid,a.percode,a.`enable`,a.creator,a.creatdate,a.modifier,a.modifdate,b.`language`,b.`value` FROM permission a LEFT JOIN permissionres b ON a.autoid=b.permissionid WHERE havedelete=0 and a.autoid={AutoId}").ToList();


        public double GetSeq()
        {
            Permission permission = this.dbConnection.QueryFirstOrDefault<Permission>("SELECT * FROM permission WHERE havedelete=0  ORDER BY autoid DESC LIMIT 0,1");
            if (permission is null) return 1;
            else return (permission.Sequence is null ? 1 : permission.Sequence.Value + 1);
        }

        public long Add(Permission data) => this.dbConnection.Insert(data);

        public bool Add(List<PermissionRes> res)
        {
            this.dbConnection.Execute($"delete  from `permissionres` where permissionid = {res.FirstOrDefault().PermissionId};");
            if (res.Any())
            {

                return this.dbConnection.Insert(res) >= 0;
            }
            return true;
        }

        public bool Add(List<ButtonsPermission> opertions, long PermissionId)
        {
            this.dbConnection.Execute($"delete  from buttons_permission where permissionid = {PermissionId};");
            if (opertions.Any())
            {
                return this.dbConnection.Insert(opertions) >= 0;
            }
            return true;
        }

        public bool IsPermissionCodeRepeat(long AutoId, string PerCode)
        {
            string sql = $"SELECT * FROM permission WHERE percode='{PerCode}'";
            if (AutoId != 0)
            {
                sql = $"{sql} AND autoid != {AutoId}";
            }
            return dbConnection.Query<Permission>(sql).Any();
        }

        public List<PagePermissionTable> Pages(QueryModel queryModel, out long Total)
        {
            Total = 0;
            string where = "";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   AND a.percode LIKE '%{queryModel.KeyWord}%' OR b.value LIKE '%{queryModel.KeyWord}%' ";
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "a.AutoId";
                queryModel.IsAsc = false;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (queryModel.paramters.Any())
            {
                queryModel.paramters.ForEach(p =>
                {
                    where += $"  and {p.Label} like '%{p.Value}%'  ";
                });
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"select count(a.AutoId) as cnt  FROM permission a LEFT 
                          JOIN permissionres b ON a.autoid=b.permissionid 
                          AND b.`language` = '{this.Global.Language}'  WHERE havedelete=0
                        {where}  ;");
            sql.Append(@$"SELECT a.autoid,a.percode,a.`enable`,a.creator,a.creatdate,a.modifier,a.modifdate,b.`language`,b.`value` FROM permission a LEFT 
                          JOIN permissionres b ON a.autoid=b.permissionid 
                          AND b.`language` = '{this.Global.Language}'  WHERE havedelete=0
                        {where}  ORDER BY {queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{ queryModel.PageSize} ;");
            using (var reader = dbConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PagePermissionTable> pageModules = reader.Read<PagePermissionTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }
        public List<ButtonsPermission_OutPut> GetButtons(long PermissionId) => this.dbConnection.Query<ButtonsPermission_OutPut>($"select a.btnid,b.`value` from buttons_permission a LEFT JOIN buttonres b on a.btnid=b.btnid where permissionid={PermissionId} and b.`language`='{Global.Language }'").ToList();
    }
}
